package com.relytosoft.mizar.media.common.emqx.callback;

import com.relytosoft.mizar.media.common.emqx.client.EmqxClient;
import com.relytosoft.mizar.media.common.emqx.config.MqttConfiguration;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Jierry
 * @version 2022/4/22.
 */
@Component
public class PushCallback implements MqttCallback {

    private static final Logger log = LoggerFactory.getLogger(PushCallback.class);

    @Resource
    private MqttConfiguration mqttConfiguration;

    @Override
    public void connectionLost(Throwable cause) {        // 连接丢失后，一般在这里面进行重连
        log.info("连接断开，正在重连");
        MqttClient client;
        try {
            client = new MqttClient(mqttConfiguration.getHost(), mqttConfiguration.getClientid(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            if (mqttConfiguration.getUsername() != null) {
                options.setUserName(mqttConfiguration.getUsername());
            }
            if (mqttConfiguration.getPassword() != null) {
                options.setPassword(mqttConfiguration.getPassword().toCharArray());
            }
            options.setConnectionTimeout(mqttConfiguration.getTimeout());
            options.setKeepAliveInterval(mqttConfiguration.getKeepalive());
            EmqxClient.setClient(client);
        } catch (MqttException e) {
            log.info("重连失败，"+e.getMessage());
            throw new RuntimeException(e);
        }

    }

    /**
     * 发送消息，消息到达后处理方法
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        //int messageId = token.getMessageId();
        //String[] topics = token.getTopics();
        log.info("EMQX消息发送完成");
    }

    /**
     * 订阅主题接收到消息处理方法
     * @param topic
     * @param message
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        // subscribe后得到的消息会执行到这里面,这里在控制台有输出
        String messageStr = new String(message.getPayload());
        // messageDistribute.distribute(topic, messageStr);
        log.info("接收的主题：" + topic +  ";接收到的信息：" + messageStr);
    }
}
